/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.niepan.modules.sys.controller;

import cn.hutool.core.codec.Base64;
import com.niepan.common.utils.R.ApiResponse;
import com.niepan.common.utils.R.Result;
import com.niepan.modules.sys.entity.SysUserEntity;
import com.niepan.modules.sys.form.SysLoginForm;
import com.niepan.modules.sys.service.SysCaptchaService;
import com.niepan.modules.sys.service.SysUserService;
import com.niepan.modules.sys.service.SysUserTokenService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 登录相关
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
public class SysLoginController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;
	@Autowired
	private SysCaptchaService sysCaptchaService;

	@GetMapping("hello")
	public String hello(){
		return "hello";
	}

	/**
	 * 验证码
	 */
	@GetMapping("/captcha")
	public ApiResponse captcha(HttpServletResponse response)throws IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		String uuid = UUID.randomUUID().toString().replaceAll("-", "");

		//获取图片验证码
		BufferedImage image = sysCaptchaService.getCaptcha(uuid);
		Map<String,Object> map = new HashMap<>();
		FastByteArrayOutputStream os = new FastByteArrayOutputStream();
		ImageIO.write(image, "jpg", os);

		map.put("image",Base64.encode(os.toByteArray()));
		map.put("uuid", uuid);
		IOUtils.closeQuietly(os);

		return Result.success(map);
	}

	/**
	 * 登录
	 */
	@PostMapping("/sys/login")
	public ApiResponse login(@RequestBody SysLoginForm form)throws IOException {
		//to B 内网，暂时不用验证码
//		boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
//		if(!captcha){
//			return Result.error("验证码不正确");
//		}

		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
			return Result.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0){
			return Result.error("账号已被锁定,请联系管理员");
		}

		//生成token，并保存到数据库
//		return sysUserTokenService.createToken(user.getUserId());
		List<Map<String,Object>> list =  sysUserService.getMenuByUsername(form.getUsername());
		return Result.success(list);
	}


	/**
	 * 退出
	 */
	@PostMapping("/sys/logout")
	public ApiResponse logout() {
		sysUserTokenService.logout(1);
		return Result.success();
	}

	/**
	 * 获取用户菜单
	 * @param username
	 * @return
	 */
	@GetMapping("/sys/getMenu")
	public ApiResponse getMenu(@RequestParam("username") String username){
		List<Map<String, Object>> menuByUsername = sysUserService.getMenuByUsername(username);
		return Result.success(menuByUsername);
	}


}
